/**
 *  配置文件类，用来获取项目路径、模块配置文件、服务器配置等
 * @author yangxiao
 * @module lib/config
 */

import * as fs from 'fs';
import * as path from 'path';
import * as log from '../log/log';

let serverJsonPath = "asset/config/server.json";

export let serverID:any;
export function setServerID(value:string){
    serverID = value;
}
/**
 * 存放已经加载的配置
 */
export let _jsonFileList = {};
/**
 * 获取当前的开发模式
 */
export let isDebug = true;

export function setIsDebug(value:boolean){
    isDebug = value;
}
/**
 * 获取绝对的路径，本目录位于out的上级，也就是项目的文件夹
 * @param {string} [_path] 写入相对路径，获取根据asset下的相对路径
 * @returns
 */
export function getRootPath(_path?){
    if(_path == null){
        _path = '';
    }
    return path.resolve()+path.normalize("/"+_path);
}


/**
 * 获得资源文件夹的路径
 * 
 * @param {string} [_path] 写入相对路径，获取根据asset下的相对路径
 * @returns
 */
export function getAssetPath(_path?){
    if(_path == null){
        _path = '';
    }
    return  getRootPath()+path.normalize("/asset/"+_path); 
}

/**
 * 获取当前服务器的本地配置文件，写入相对目录
 * @param {String} value 路径 如：asset/xxx/xxxx.json
 * @param {Boolean} isCacheRefresh 是否刷新缓存，未来用于网络刷新配置
 */
export function getJsonFile(value:string,isCacheRefresh=false):any{

    if(_jsonFileList[value] && !isCacheRefresh){
        return _jsonFileList[value];
    }
    try{
        _jsonFileList[value] = require(getRootPath()+path.normalize(value));
        return _jsonFileList[value];
    }catch(e){
        log.error(e);
    }
    return null;
}

/**
 * 获取其他配置文件
 */
export function getOtherFile(value:string):any{
    if(!fs.existsSync(getRootPath()+path.normalize(value))){
        return null;
    }
    return fs.readFileSync(getRootPath()+path.normalize(value),"utf-8");   
}

/**
 * 服务器配置文件接口
 */
module LibConfig{
    export interface ServerConfig{
        serverMaster:masterServerConfig;
        serverChat:masterServerConfig;
        ServerGameList:masterServerConfig[];
        mysql:mysqlConfig[];
        redis:redisConfig;
    }
    interface masterServerConfig{
        id:string;
        domain:string;
        port:number;
        clientPort:number;
        host:string;
    }
    interface mysqlConfig{
        host: string;
        user: string;
        pwd: string;
        dbName: string; 
        char:string;
    }
    interface redisConfig{
        host:string;
        port:number;
        user:string;
        pwd:string;
        dbName: string; 
        prefix:string;
    }
}
/**
 * 获取服务器配置信息
 */
export function getServerConfig():LibConfig.ServerConfig{
    let config = getJsonFile(serverJsonPath);
    if(config==null){
        log.error("file or format - ",serverJsonPath);
    }
    if(isDebug){
       return config.development;
    }
    return config.production;
}



